<template>
  <div class="menu-wrapper">
    <el-form ref="receiverForm" :model="form" :rules="rules" label-width="100px">
      <div v-if="!memberId" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="memberId">
            <el-select v-model="form.memberId" style="width: 100%;" :disabled="afferentMember" clearable placeholder="请选择用户名" filterable :filter-method="queryMember">
              <el-option v-for="item in memberIdOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货人" prop="consignee">
            <el-input v-model="form.consignee" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" type="number" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="选择位置" prop="building">
            <el-button v-show="!form.building" type="primary" round @click="mapShowFn"><i class="el-icon-map-location" /> 点击选择</el-button>
            <!-- <el-input v-model="form.address" @click="mapShowFn"/> -->
            <el-tooltip class="item" effect="dark" content="点击重新选择位置" placement="top">
              <el-link v-show="form.building" type="primary" :underline="false" @click="mapShowFn">{{ form.building }}</el-link :underline="false">
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="门牌号" prop="roomNumber">
            <el-input v-model="form.roomNumber" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="设为默认地址" prop="isDefault">
            <el-switch
              v-model="form.isDefault"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button v-permission="['member.query']" type="primary" :loading="clicked" @click="saveReceiver('receiverForm')">
          完 成
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="位置信息"
      :visible.sync="mapShow"
      top="5vh"
      width="800px"
      :before-close="handleClose"
      append-to-body
    >
      <Map :initcenter="[form.lng, form.lat]" @getMap="getMap" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped>
  .menu-wrapper {
    margin: 15px;
  }
</style>
<script>
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import Distpicker from '@/components/Distpicker/Distpicker'
import Map from '@/components/GaodeMap/index'
import { save } from '@/api/receiver'
import { list as memberList, find as memberFind } from '@/api/member'
import permission from '@/directive/permission/index.js' // 权限判断指令
export default {
  name: 'Add',
  filters: {},
  directives: { permission },
  components: { Map, Distpicker },
  props: [
    'memberId', 'pathType'
  ],
  data() {
    return {
      clicked: false, // 按钮防双击
      mapShow: false,
      tempLng: '',
      tempLat: '',
      tempAddress: '',
      tempAreaId: '',
      tempAois: '',
      tempAreaName: '',
      memberMark: false, // 防抖
      memberIdOptions: [],
      afferentMember: false, // 判断是否由外界传入
      form: {
        address: '', // 详细地址
        areaName: '',
        areaId: '', // 地区
        building: '', // 小区/大楼
        consignee: '',
        isDefault: true, // 是否默认
        lat: '', // 纬度
        level: '', // 楼层
        lng: '', // 经度
        mapLineId: '', // 地区
        memberId: '', // 会员
        phone: '', // 电话
        roomNumber: '' // 门牌号

      },
      rules: {
        memberId: [
          { required: true, message: '请选择用户名', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        building: [
          { required: true, message: '请选择位置', trigger: 'blur' }
        ],
        roomNumber: [
          { required: true, message: '请输入门牌号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initMemberData()
    this.queryMember()
  },
  methods: {
    initMemberData() {
      // this.memberId = this.$route.query.memberId
      if (!utils.isNull(this.memberId) || !utils.isNull(this.$route.query.memberId)) {
        this.afferentMember = true
        this.form.memberId = Number(this.memberId) || Number(this.$route.query.memberId)
        memberFind(this.form.memberId).then(res => {
          this.memberIdOptions.push(res.data.member)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    mapShowFn() {
      this.mapShow = !this.mapShow
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    getMap(lng, lat, addressData) {
      // console.log(lng, lat, addressData)
      // 定义变量保存经纬度和地址
      this.tempLng = lng
      this.tempLat = lat
      // this.tempAddress = addressData.formattedAddress
      this.tempAreaId = addressData.addressComponent.adcode
      // addressData.aois.length !== 0 ? this.tempAois = addressData.aois[0].name : this.tempAois
      this.tempAois = addressData.formattedAddress
      this.tempAreaName = `${addressData.addressComponent.province}${addressData.addressComponent.city}${addressData.addressComponent.district}`
    },
    savelngLat() {
      this.form.lng = this.tempLng
      this.form.lat = this.tempLat
      // this.form.address = this.tempAddress
      this.form.areaId = this.tempAreaId
      this.form.building = this.tempAois
      this.form.areaName = this.tempAreaName
      this.mapShowFn()
    },
    queryMember(query) { // 搜索客户
      // console.log(query)
      clearTimeout(this.memberMark)
      this.memberMark = setTimeout(() => {
        this.memberIdOptions = []
        memberList({ name: query }).then(res => {
          this.memberIdOptions = res.data.data
        }).catch(err => {
          console.log(err)
        })
      }, 300)
    },
    saveReceiver(form) {
      var _this = this
      console.log(this.memberId)
      if (this.memberId != undefined) {
        this.form.memberId = this.memberId
      }
      console.log(this.pathType)
      this.$refs[form].validate(valid => {
        if (valid) {
          this.clicked = true
          const address = this.form.building + this.form.roomNumber
          const params = {
            address,
            areaName: this.form.areaName,
            consignee: this.form.consignee,
            isDefault: this.form.isDefault,
            lat: this.form.lat,
            lng: this.form.lng,
            memberId: this.form.memberId,
            phone: this.form.phone,
            roomNumber: this.form.roomNumber,
            building: this.form.building,
            createDate: new Date()
          }
          save(params).then(res => {
            console.log(res)
            if (res.type == 'success') {
              if (_this.pathType == undefined) {
                EventBus.$emit('receiver-add', res.data)
                this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                  this.$router.push({
                    path: '/receiver/list'
                  })
                })// 关闭当前tab回到列表
              } else {
                this.$emit('orderReceiver', res)
              }
            } else { this.$message({ message: res.content, offset: 120, center: true }) }
            this.clicked = false
          }).catch(err => {
            this.clicked = false
            console.log(err)
          })
        }
      })
    }
  }
}
</script>
